package com.weme.mine.view

import android.content.Context
import android.graphics.drawable.Drawable
import android.text.TextUtils
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.viewpager2.widget.ViewPager2
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.Target
import com.weme.common.util.*
import com.weme.common.view.SmoothConstraintLayout
import com.weme.common.view.SmoothImageView
import com.weme.mine.R
import dev.kratos.api.user_server.v1.Media
import net.lucode.hackware.magicindicator.MagicIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.CommonPagerTitleView


class UserAlbumIndicator @JvmOverloads constructor(
    context: Context,
    set: AttributeSet? = null,
) : MagicIndicator(context, set) {

    private var mViewPager: ViewPager2? = null

    private var labels: List<Media>? = null

    fun attachViewPager(viewPager: ViewPager2, label: List<Media>,isMy :Boolean) {
        mViewPager = viewPager
        labels = label
        clipChildren = false

        init(viewPager.context,isMy)
        bind(mViewPager)
    }

    private fun init(context: Context,isMy: Boolean) {
        val navigator = CommonNavigator(context) //navigator.isAdjustMode = true
        navigator.isSkimOver = true
        navigator.adapter = object : CommonNavigatorAdapter() {
            override fun getCount() = labels?.size ?: 0

            override fun getTitleView(context: Context, index: Int): IPagerTitleView {
                val commonPagerTitleView = CommonPagerTitleView(context)
                val customLayout: View = LayoutInflater.from(context).inflate(R.layout.item_preview, null)
                customLayout.alpha = 0f
                val simView = customLayout.findViewById<SmoothImageView>(R.id.simView)
                val calView = customLayout.findViewById<ConstraintLayout>(R.id.calView)
                val simMc = customLayout.findViewById<SmoothConstraintLayout>(R.id.simMc)

                val imLock = customLayout.findViewById<ImageView>(R.id.imLock)
                val imVideoBk = customLayout.findViewById<ImageView>(R.id.imVideoBk)
                imVideoBk.setInvisible(!labels!![index].type.isTypeImg() || TextUtils.isEmpty(labels!![index].url))

                val layoutParams = simView.layoutParams as MarginLayoutParams
                var margins = 0
                if (!labels!![index].type.isTypeImg() ||TextUtils.isEmpty(labels!![index].url)){
                    margins = 8
                }
                layoutParams.setMargins(margins, margins, margins, margins)

                if(labels!![index].url.equals("")){
                    customLayout.fadeIn()
                    imLock.gone()
                }else if(!labels!![index].type.isTypeImg()&& UserMKHelper.decodeLong(UserMKHelper.VIP_LEVEL)==0L&&!isMy){
                    Glide.with(context)
                        .load(labels!![index].url)
                        .sizeMultiplier(0.5f)
                        .override(200, 200)
                        .error(com.example.resources.R.mipmap.icon_mine_pic_null)
                        .apply(RequestOptions
                            .placeholderOf(com.example.resources.R.drawable.icon_album_null)
                            .transform(GlideBlurTransformer(20, 2))
                        )
                        .listener(object : RequestListener<Drawable> {
                            override fun onResourceReady(resource: Drawable, model: Any, target: Target<Drawable>?, dataSource: DataSource, isFirstResource: Boolean): Boolean {
                                customLayout.fadeIn()
                                 return false
                            }

                            override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>, isFirstResource: Boolean): Boolean {
                                return false
                            }
                        })
                        .into(simView)

                    imLock.visible()
                }else{
                    customLayout.fadeIn()
                    if(TextUtils.isEmpty(labels!![index].url)){
                        simView.setImageResource(com.example.resources.R.mipmap.icon_head_null)
                    }else{
                        Glide.with(context)
                            .load(labels!![index].url.toString())
                            .apply(requestOptions)
                            .listener(object : RequestListener<Drawable> {
                                override fun onResourceReady(resource: Drawable, model: Any, target: Target<Drawable>?, dataSource: DataSource, isFirstResource: Boolean): Boolean {
                                    customLayout.fadeIn()
                                    return false
                                }

                                override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>, isFirstResource: Boolean): Boolean {
                                    return false
                                }
                            })
                            //  .diskCacheStrategy(DiskCacheStrategy.ALL) // 根据需求设置缓存策略
                            .into(simView)
                    }

                    imLock.gone()
                }

                commonPagerTitleView.addView(customLayout)
                commonPagerTitleView.setOnClickListener {
                    mViewPager?.currentItem = index
                }
                commonPagerTitleView.onPagerTitleChangeListener = object : CommonPagerTitleView.OnPagerTitleChangeListener {
                    override fun onSelected(index: Int, totalCount: Int) {
                  //      customLayout.alpha = 1f // 在选中时将透明度设置为0
                        simMc.gone()
                    }

                    override fun onDeselected(index: Int, totalCount: Int) {
                      //  customLayout.alpha = 0.7f // 在未选中时将透明度设置为0.5
                        simMc.visible()
                    }

                    override fun onLeave(index: Int, totalCount: Int, leavePercent: Float, leftToRight: Boolean) {
                        // 当 leavePercent 为 0 时，scale 为 1.2；当 leavePercent 为 1 时，scale 为 1
                        val scale = 1.1f - 0.1f * leavePercent
                        calView.scaleX = scale
                        calView.scaleY = scale
                    }

                    override fun onEnter(index: Int, totalCount: Int, enterPercent: Float, leftToRight: Boolean) {
                        // 当 enterPercent 为 0 时，scale 为 1；当 enterPercent 为 1 时，scale 为 1.2
                        val scale = 1f + 0.1f * enterPercent
                        calView.scaleX = scale
                        calView.scaleY = scale
                    }


                }

                return commonPagerTitleView
            }

            override fun getIndicator(p0: Context): IPagerIndicator? {
                return null
            }
        }
        setNavigator(navigator)
    }
}